<template>
  <div class="app-container">
    <el-card>
      <!-- 搜索表单 -->
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" class="search-form">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="queryParams.username" placeholder="请输入用户名" clearable style="width: 240px" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="queryParams.phone" placeholder="请输入手机号码" clearable style="width: 240px" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 240px">
            <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <el-row :gutter="10" class="mb-3">
        <el-col :span="1.5">
          <el-button type="primary" :icon="Plus" @click="handleAdd">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" :icon="Delete" :disabled="selectedIds.length === 0" @click="handleBatchDelete">批量删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" :icon="Download" @click="handleExport">导出</el-button>
        </el-col>
      </el-row>

      <!-- 表格 -->
      <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="用户编号" align="center" prop="id" width="80" />
        <el-table-column label="用户名称" align="center" prop="username" :show-overflow-tooltip="true" />
        <el-table-column label="用户昵称" align="center" prop="nickname" :show-overflow-tooltip="true" />
        <el-table-column label="部门" align="center" prop="deptName" :show-overflow-tooltip="true" />
        <el-table-column label="手机号码" align="center" prop="phone" width="120" />
        <el-table-column prop="status" label="状态" align="center" width="100">
          <template #default="scope">
            <dict-tag dict-type="sys_normal_disable" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" width="160">
          <template #default="scope">
            <span>{{ formatDateTime(scope.row.createdAt) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="sex" label="性别" align="center" width="100">
          <template #default="scope">
            <dict-tag dict-type="sys_user_sex" :value="scope.row.sex" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="280" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button type="primary" link :icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button type="primary" link :icon="Key" @click="handleRole(scope.row)">角色</el-button>
            <el-button type="primary" link :icon="Lock" @click="handleResetPwd(scope.row)">重置密码</el-button>
            <el-button type="danger" link :icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-if="total > 0"
        :total="total"
        v-model:page="queryParams.page"
        v-model:limit="queryParams.limit"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改用户对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body>
      <el-form ref="userFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" :disabled="form.id !== null" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
          <el-tree-select
            v-model="form.deptId"
            :data="deptOptions"
            :props="{ label: 'name', children: 'children', value: 'id' }"
            value-key="id"
            placeholder="请选择部门"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号码" maxlength="11" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!form.id">
          <el-input v-model="form.password" placeholder="请输入密码" type="password" />
        </el-form-item>
        <el-form-item label="用户性别" prop="sex">
          <dict-radio
            v-model="form.sex"
            dict-type="sys_user_sex"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <dict-radio
            v-model="form.status"
            dict-type="sys_normal_disable"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="dialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" v-model="roleDialog.visible" width="500px" append-to-body>
      <el-form label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="roleDialog.username" disabled />
        </el-form-item>
        <el-form-item label="角色列表">
          <el-transfer
            v-model="roleDialog.selectedRoleIds"
            :titles="['可选角色', '已选角色']"
            :data="roleDialog.roleOptions"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitUserRole">确 定</el-button>
          <el-button @click="roleDialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog title="重置密码" v-model="pwdDialog.visible" width="500px" append-to-body>
      <el-form ref="pwdFormRef" :model="pwdDialog.form" :rules="pwdDialog.rules" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="pwdDialog.username" disabled />
        </el-form-item>
        <el-form-item label="新密码" prop="password">
          <el-input v-model="pwdDialog.form.password" placeholder="请输入新密码" type="password" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="pwdDialog.form.confirmPassword" placeholder="请确认密码" type="password" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitResetPwd">确 定</el-button>
          <el-button @click="pwdDialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete, Download, Key, Lock } from '@element-plus/icons-vue'
import { 
  getUserList, 
  getUserDetail, 
  createUser, 
  updateUser, 
  deleteUser, 
  updateUserStatus, 
  resetUserPassword,
  exportUserList,
  getUserRoles,
  assignUserRoles
} from '@/api/user'
import { getDeptTree } from '@/api/dept'
import { getRoleList } from '@/api/role'
import { validPhone, validEmail } from '@/utils/validate'
import Pagination from '@/components/Pagination/index.vue'
import useDict from '@/hooks/useDict'

// 状态数据字典
const statusOptions = [
  { value: 1, label: '正常' },
  { value: 0, label: '停用' }
]

// 查询参数
const queryParams = reactive({
  page: 1,
  limit: 10,
  username: '',
  phone: '',
  status: null
})

// 日期范围
const dateRange = ref([])

// 表格数据
const userList = ref([])
const deptOptions = ref([])
const loading = ref(false)
const total = ref(0)
const selectedIds = ref([])
const queryFormRef = ref(null)
const userFormRef = ref(null)
const pwdFormRef = ref(null)

// 表单参数
const form = reactive({
  id: null,
  username: '',
  nickname: '',
  deptId: null,
  phone: '',
  email: '',
  password: '',
  status: 1,
  remark: '',
  sex: null
})

// 表单校验规则
const rules = {
  username: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度必须介于 2 和 20 之间', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '昵称不能为空', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度必须介于 6 和 20 之间', trigger: 'blur' }
  ],
  phone: [
    { validator: (rule, value, callback) => {
      if (value && !validPhone(value)) {
        callback(new Error('请输入正确的手机号码'))
      } else {
        callback()
      }
    }, trigger: 'blur' }
  ],
  email: [
    { validator: (rule, value, callback) => {
      if (value && !validEmail(value)) {
        callback(new Error('请输入正确的邮箱地址'))
      } else {
        callback()
      }
    }, trigger: 'blur' }
  ]
}

// 用户表单对话框
const dialog = reactive({
  title: '',
  visible: false
})

// 角色分配对话框
const roleDialog = reactive({
  visible: false,
  userId: null,
  username: '',
  roleOptions: [],
  selectedRoleIds: []
})

// 重置密码对话框
const pwdDialog = reactive({
  visible: false,
  userId: null,
  username: '',
  form: {
    password: '',
    confirmPassword: ''
  },
  rules: {
    password: [
      { required: true, message: '密码不能为空', trigger: 'blur' },
      { min: 6, max: 20, message: '密码长度必须介于 6 和 20 之间', trigger: 'blur' }
    ],
    confirmPassword: [
      { required: true, message: '确认密码不能为空', trigger: 'blur' },
      { 
        validator: (rule, value, callback) => {
          if (value !== pwdDialog.form.password) {
            callback(new Error('两次输入的密码不一致'))
          } else {
            callback()
          }
        }, 
        trigger: 'blur' 
      }
    ]
  }
})

// 字典数据
const { dicts } = useDict('sys_normal_disable', 'sys_user_sex')

// 格式化日期时间
const formatDateTime = (value) => {
  if (!value) return ''
  return new Date(value).toLocaleString()
}

// 获取用户列表
const getList = async () => {
  loading.value = true
  try {
    // 处理日期范围
    const params = { ...queryParams }
    if (dateRange.value && dateRange.value.length === 2) {
      params.beginTime = dateRange.value[0]
      params.endTime = dateRange.value[1]
    }
    
    const res = await getUserList(params)
    userList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 获取部门树
const getDeptTreeData = async () => {
  try {
    const res = await getDeptTree()
    deptOptions.value = res.data
  } catch (error) {
    console.error('获取部门树失败:', error)
    ElMessage.error('获取部门树失败')
  }
}

// 获取角色列表
const getRoles = async () => {
  try {
    const res = await getRoleList({ page: 1, limit: 100 })
    roleDialog.roleOptions = res.data.list.map(role => {
      return {
        key: role.id,
        label: role.name
      }
    })
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  }
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.page = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  dateRange.value = []
  queryFormRef.value.resetFields()
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 表单重置
const resetForm = () => {
  userFormRef.value?.resetFields()
  Object.assign(form, {
    id: null,
    username: '',
    nickname: '',
    deptId: null,
    phone: '',
    email: '',
    password: '',
    status: 1,
    remark: '',
    sex: null
  })
}

// 状态修改
const handleStatusChange = async (row) => {
  try {
    await updateUserStatus(row.id, row.status)
    ElMessage.success(`修改用户状态成功`)
  } catch (error) {
    console.error('修改用户状态失败:', error)
    ElMessage.error('修改用户状态失败')
    row.status = row.status === 1 ? 0 : 1
  }
}

// 新增按钮操作
const handleAdd = () => {
  resetForm()
  dialog.title = '添加用户'
  dialog.visible = true
}

// 修改按钮操作
const handleUpdate = async (row) => {
  resetForm()
  dialog.title = '修改用户'
  dialog.visible = true
  
  try {
    const res = await getUserDetail(row.id)
    Object.assign(form, res.data)
  } catch (error) {
    console.error('获取用户详情失败:', error)
    ElMessage.error('获取用户详情失败')
  }
}

// 提交表单
const submitForm = () => {
  userFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        if (form.id) {
          // 修改
          await updateUser(form.id, form)
          ElMessage.success('修改用户成功')
        } else {
          // 新增
          await createUser(form)
          ElMessage.success('新增用户成功')
        }
        dialog.visible = false
        getList()
      } catch (error) {
        console.error(form.id ? '修改用户失败:' : '新增用户失败:', error)
        ElMessage.error(form.id ? '修改用户失败' : '新增用户失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 删除按钮操作
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除用户"${row.username}"吗?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteUser(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 批量删除操作
const handleBatchDelete = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  
  ElMessageBox.confirm(`确认删除选中的${selectedIds.value.length}个用户吗?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 逐个删除选中的用户
      await Promise.all(selectedIds.value.map(id => deleteUser(id)))
      ElMessage.success('批量删除成功')
      getList()
    } catch (error) {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  })
}

// 导出用户
const handleExport = () => {
  ElMessageBox.confirm('是否确认导出所有用户数据?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 处理日期范围
    const params = { ...queryParams }
    if (dateRange.value && dateRange.value.length === 2) {
      params.beginTime = dateRange.value[0]
      params.endTime = dateRange.value[1]
    }
    
    exportUserList(params)
  })
}

// 角色按钮操作
const handleRole = async (row) => {
  roleDialog.userId = row.id
  roleDialog.username = row.username
  roleDialog.visible = true
  roleDialog.selectedRoleIds = []

  try {
    // 获取用户已分配的角色
    const res = await getUserRoles(row.id)
    roleDialog.selectedRoleIds = res.data.map(role => role.id)
  } catch (error) {
    console.error('获取用户角色失败:', error)
    ElMessage.error('获取用户角色失败')
  }
}

// 提交用户角色
const submitUserRole = async () => {
  try {
    await assignUserRoles(roleDialog.userId, roleDialog.selectedRoleIds)
    ElMessage.success('分配角色成功')
    roleDialog.visible = false
  } catch (error) {
    console.error('分配角色失败:', error)
    ElMessage.error('分配角色失败')
  }
}

// 重置密码按钮操作
const handleResetPwd = (row) => {
  pwdDialog.userId = row.id
  pwdDialog.username = row.username
  pwdDialog.form.password = ''
  pwdDialog.form.confirmPassword = ''
  pwdDialog.visible = true
}

// 提交重置密码
const submitResetPwd = () => {
  pwdFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await resetUserPassword(pwdDialog.userId, pwdDialog.form.password)
        ElMessage.success('重置密码成功')
        pwdDialog.visible = false
      } catch (error) {
        console.error('重置密码失败:', error)
        ElMessage.error('重置密码失败')
      }
    }
  })
}

onMounted(() => {
  getList()
  getDeptTreeData()
  getRoles()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.mb-3 {
  margin-bottom: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style> 